<?php
namespace app\admin\controller;
use app\admin\logic\IntegralTotalLogic;

/**
 * 积分统计api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/11/27
 * Time: 16:00
 */
class IntegralTotal extends Base {

    public function __construct(){
        parent::__construct();
        $this->it_logic = new IntegralTotalLogic();
    }

    /**
     * 获取积分统计
     * @return \think\response\Json
     */
    public function ajax_get_it(){
        $params = input();
        $r = $this->check_admin_token($params);
        if ($r['code'] != 1) {
            return json($r);
        }

        //获取积分统计
        $r = $this->it_logic->get_it($params);

        $data['list'] = $r['data']['list'];
        $data['total_num'] = $r['data']['total_num'];;
        return json($this->it_logic->get_response(1,'OK',$data));
    }

    /**
     * 导出积分统计
     * http://127.0.0.1/mandiao-mini-api/public/admin-integral_total-export_it?token=e916a6039bff505bacaf5def2bb8435f
     * @return \think\response\Json
     */
    public function export_it(){
        $params = input();
        $r = $this->check_admin_token($params);
        if($r['code'] != 1){
            return json($r);
        }

        //获取积分统计
        $r = $this->it_logic->get_it($params);
        $list = $r['data']['list'];

        $row = ['部门名称','姓名','总积分'];

        $export_data = [];
        foreach($list as $k => $v){
            $export_data[$k]['department'] = $v['department'];
            $export_data[$k]['username'] = $v['username'];
            $export_data[$k]['total_integral'] = $v['total_integral'];
        }
        array_unshift($export_data,$row);

        $file_name = '积分统计' . date('YmdHi') . '.xlsx';
        $r = $this->it_logic->gen_it_excel($file_name,$export_data);

        //$this->redirect(\think\facade\Request::root(true) . '/' . $file_name);
        return json($this->it_logic->get_response(1,'导出成功'));
    }

    /**
     * 积分操作
     * @return \think\response\Json
     */
    public function ajax_integral_operate(){
        $params = input();
        $r = $this->check_admin_token($params);
        if ($r['code'] != 1) {
            return json($r);
        }

        //积分操作规则
        $r = $this->it_logic->check_integral_operate_rule($params);
        if(!$r['code']){
            return json($r);
        }

        $ip_data = [];
        $ip_data['openid'] = $params['openid'];
        $ip_data['integral'] = trim($params['integral']);
        $ip_data['explain'] = trim($params['explain']);
        $ioid =  model('integral_operate')->insertGetId($ip_data);
        if($ioid){
            //更新积分操作积分
            $si = new \app\common\controller\SaveIntegral();
            $r = $si->save_io_integral($ioid);

            return json($this->it_logic->get_response(1,'操作成功'));
        }
        return json($this->it_logic->get_response(1,'操作成功'));
    }
}